﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;

namespace ProxyList
{
    public class PicParser
    {
        private Bitmap[] digits;

        public PicParser()
        {
            digits = LoadDigits();
        }

        public string Execute(Bitmap bmp)
        {
            string port = "";

            for (int i = 0; i < 5; i++)
            {
                Bitmap dig_bmp = ExtractNumImage(bmp, i);
                int dig = GetDigit(dig_bmp);
                if (dig >= 0)
                {
                    port += dig.ToString();
                }
            }
            return port;
        }

        private Bitmap[] LoadDigits()
        {
            Bitmap[] bitmaps = new Bitmap[10];
            for (int i = 0; i < 10; i++)
            {
                bitmaps[i] = new Bitmap("dig-" + i.ToString() + ".gif");
            }
            return bitmaps;
        }

        private Bitmap ExtractNumImage(Bitmap Sour, int Pos)
        {
            int x_off = Pos * 6;
            Bitmap bmp = new Bitmap(5, 8);
            for (int x = 0; x < 5; x++)
            {
                for (int y = 3; y < 11; y++)
                {
                    bmp.SetPixel(x, y - 3, Sour.GetPixel(x + x_off, y));
                }
            }
            return bmp;
        }

        private int GetDigit(Bitmap Bmp)
        {
            for (int i = 0; i < 10; i++)
            {
                if (CompareBmp(Bmp, digits[i]))
                    return i;
            }
            return -1;
        }

        private bool CompareBmp(Bitmap Sour, Bitmap Dest)
        {
            for (int x = 0; x < 5; x++)
            {
                for (int y = 0; y < 8; y++)
                {
                    if (Sour.GetPixel(x, y) != Dest.GetPixel(x, y))
                    {
                        return false;
                    }
                }
            }
            return true;
        }
    }
}
